<?php
namespace app\common\model\newmodel;

use think\Model;
use think\Db;
use app\common\model\newmodel\UserFactory;
use app\common\model\newmodel\UserAgency;
use app\api\controller\Pub;
class User extends Model
{
    protected $table = 'user';
    protected $pk = 'UserId';
    
    /**
     * 获取工厂员工列表
     */
    public static function getFactoryStaffList($userId, $page = 1, $pageSize = 10, $keyword = '')
    {
        if (empty($userId)) {
            return ['code' => 0, 'msg' => '用户ID不能为空'];
        }
        
        // 获取当前用户所属的工厂ID
        $factoryId = UserFactory::getFactoryIdByUserId($userId);
        if (!$factoryId) {
            return ['code' => 0, 'msg' => '未绑定工厂'];
        }
        
        // 获取该工厂下所有员工ID
        $userIds = UserFactory::getUserIdsByFactoryId($factoryId);
        if (empty($userIds)) {
            return ['code' => 1, 'msg' => 'success', 'data' => []];
        }
        
        $query = self::whereIn('UserId', $userIds)
                    ->where('Role',302);
        
        if (!empty($keyword)) {
            $query->where('Name', 'like', "%{$keyword}%");
        }
        $list = $query->field([
                        'UserId',
                        'Iphone', 
                        'Name',
                        'Sex',
                    ])
                    ->order('UserId desc')
                    ->paginate([
                        'list_rows' => $pageSize,
                        'page' => $page
                    ]);
        
        $data = $list->toArray();
        return ['code' => 1, 'msg' => 'success', 'data' => $data];
    }
    
    /**
     * 获取代理商员工列表
     */
    public static function getAgencyStaffList($userId, $page = 1, $pageSize = 10, $keyword = '')
    {
        if (empty($userId)) {
            return ['code' => 0, 'msg' => '用户ID不能为空'];
        }
        
        // 获取当前用户所属的代理商ID
        $agencyId = UserAgency::getAgencyIdByUserId($userId);
        if (!$agencyId) {
            return ['code' => 0, 'msg' => '未绑定代理商'];
        }
        
        // 获取该代理商下所有员工ID
        $userIds = UserAgency::getUserIdsByAgencyId($agencyId);
        if (empty($userIds)) {
            return ['code' => 1, 'msg' => 'success', 'data' => []];
        }
        
        $query = self::whereIn('UserId', $userIds)
                    ->where('Role',402);
        
        if (!empty($keyword)) {
            $query->where('Name', 'like', "%{$keyword}%");
        }
        
        $list = $query->field([
                        'UserId',
                        'Iphone', 
                        'Name',
                        'Sex',
                    ])
                    ->where('State' , 1)
                    ->order('UserId desc')
                    ->paginate([
                        'list_rows' => $pageSize,
                        'page' => $page
                    ]);
        
        $data = $list->toArray();
        return ['code' => 1, 'msg' => 'success', 'data' => $data];
    }   

    /**
     * 添加工厂员工
     */
    public static function addFactoryStaff($factoryId, $data)
    {
        if (empty($factoryId) || empty($data['Iphone']) || empty($data['Name']) || empty($data['sex'])) {
            return ['code' => 0, 'msg' => '参数不完整'];
        }
        
        $existUser = self::where('Iphone', $data['Iphone'])
                        ->find();
        if ($existUser) {
            return ['code' => 0, 'msg' => '手机号已存在'];
        }
        
        Db::startTrans();
        try {
            $user = new self();
            $user->Iphone = $data['Iphone'];
            $user->Name = $data['Name'];
            $user->Sex = $data['sex'];
            $user->Role = 302;
            $user->State = 1;
            $user->save();
            
            UserFactory::addUserFactory($user->UserId, $factoryId);
            
            Db::commit();
            return ['code' => 1, 'msg' => '工厂员工添加成功', 'data' => $user];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 0, 'msg' => '工厂员工添加失败'];
        }
    }
    
    /**
     * 添加代理商员工
     */
    public static function addAgencyStaff($agencyId, $data)
    {
        if (empty($agencyId) || empty($data['Iphone']) || empty($data['Name']) || empty($data['sex'])) {
            return ['code' => 0, 'msg' => '参数不完整'];
        }
        
        $existUser = self::where('Iphone', $data['Iphone'])
                        ->find();
        if ($existUser) {
            return ['code' => 0, 'msg' => '手机号已存在'];
        }
        
        Db::startTrans();
        try {
            $user = new self();
            $user->Iphone = $data['Iphone'];
            $user->Name = $data['Name'];
            $user->Sex = $data['sex'];
            $user->Role = 402;
            $user->State = 1;
            $user->create_time = time();
            $user->update_time = time();
            $user->save();
            
            UserAgency::addUserAgency($user->UserId, $agencyId);
            
            Db::commit();
            return ['code' => 1, 'msg' => '代理商员工添加成功', 'data' => $user];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 0, 'msg' => '代理商员工添加失败'];
        }
    }

    /**
     * 编辑员工信息
     */
    public static function editStaff($data)
    {
        if (empty($data['UserId']) || empty($data['Name']) || empty($data['Iphone']) || empty($data['sex'])) {
            return ['code' => 0, 'msg' => '参数不完整'];
        }
        
        $user = self::get($data['UserId']);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在'];
        }
        
        $user->Name = $data['Name'];
        $user->Iphone = $data['Iphone'];
        $user->Sex = $data['sex'];
        
        if ($user->save()) {
            return ['code' => 1, 'msg' => '员工信息修改成功', 'data' => $user];
        } else {
            return ['code' => 0, 'msg' => '员工信息修改失败'];
        }
    }

    /**
     * 通过jwt判断账号是否已经登录
     * 若已登录直接返回userid，没有登录则返回错误
     */
    public static function is_sessionlogin()
    {
        $token = input('token');
	    if (empty($token)) {
            return serr('口令过期，请重新登录');
        }
        $userlogininfo = Pub::getuserid(input('token'));
        return $userlogininfo;
    }


}